package com.wyp168.leetcode.treenode;


import java.nio.file.WatchEvent;
import java.util.Objects;

/**
 * @ClassName HasPathSumSolution
 * @Title TODO
 * @Description TODO
 * @Author wyp168
 * @Date 2022/10/25 19:40
 */
public class HasPathSumSolution {
    public static void main(String[] args) {
        HasPathSumSolution solution = new HasPathSumSolution();
//        TreeNode a = new TreeNode(5);
//        TreeNode b = new TreeNode(4);
//        TreeNode bb = new TreeNode(8);
//        TreeNode c = new TreeNode(11);
//        TreeNode cc = new TreeNode(13);
//        TreeNode ccc = new TreeNode(4);
//        TreeNode d = new TreeNode(7);
//        TreeNode dd = new TreeNode(2);
//        TreeNode ddd = new TreeNode(1);
//
//        a.left = b;
//        a.right = bb;
//        b.left = c;
//        bb.left = cc;
//        bb.right = ccc;
//        c.left = d;
//        c.right = dd;
//        ccc.right = ddd;

        TreeNode a = new TreeNode(1);
        TreeNode b = new TreeNode(2);
        a.left = b;

        System.out.println(solution.hasPathSum(a, 1));
    }

    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (Objects.isNull(root)) {
            return false;
        }
        int tempSum = 0;
        return dfs(root, targetSum, tempSum);
    }

    public boolean dfs(TreeNode root, int targetSum, int tempSum) {
        if (root == null) {
            return false;
        }
        if (root.left == null && root.right == null) {
            return targetSum == tempSum + root.val;
        }
        if (dfs(root.left, targetSum, tempSum + root.val) || dfs(root.right, targetSum, tempSum + root.val)) {
            return true;
        }
        return false;

    }

}
